package com.mentaleye.service.impl;

import com.mentaleye.bean.CommonResult;
import com.mentaleye.dal.model.Owner;
import com.mentaleye.dal.model.OwnerExample;
import com.mentaleye.dal.service.OwnerMapper;
import com.mentaleye.enumpackage.Status;
import com.mentaleye.service.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class OwnerServiceImpl implements OwnerService {
  @Autowired private OwnerMapper ownerMapper;
  @Transactional(propagation=Propagation.REQUIRED)
	public CommonResult editOwner(Owner
											owner, boolean add) {
		OwnerExample example=new OwnerExample();
		example.createCriteria().andPhoneEqualTo(owner.getPhone()).andStatusEqualTo(Status.NOMAL.getCode());
		if(add){
			List<Owner> owners=ownerMapper.selectByExample(example);
			if(owners!=null&&owners.size()>0){
				return new CommonResult(false,"用户手机号已经存在");
			}
			owner.setStatus(Status.NOMAL.getCode());
			ownerMapper.insertSelective(owner);
		}else{
			example=new OwnerExample();
			example.createCriteria().andUserNoEqualTo(owner.getUserNo()).andStatusEqualTo(Status.NOMAL.getCode());
			List<Owner> owners=ownerMapper.selectByExample(example);
			if(owners==null||owners.size()==0){
				return new CommonResult(false,"未找到用户");
			}
			ownerMapper.updateByExampleSelective(owner, example);
		}
		throw new RuntimeException();
		//return new CommonResult(true);
	}

	public CommonResult deleteOwner(List<String> ids) {
		OwnerExample example=new OwnerExample();
		example.createCriteria().andUserNoIn(ids).andStatusEqualTo(Status.NOMAL.getCode());
		Owner owner=new Owner();
		owner.setStatus(Status.DELETE.getCode());
		ownerMapper.updateByExampleSelective(owner, example);
		return new CommonResult(true);
	}

	public CommonResult queryOwner(String userNo, String phone) {
		OwnerExample example=new OwnerExample();
		OwnerExample.Criteria cri=example.createCriteria();
		cri.andStatusEqualTo(Status.NOMAL.getCode());
		if(!StringUtils.isEmpty(userNo)){
			cri.andUserNoEqualTo(userNo);
		}
		if(!StringUtils.isEmpty(phone)){
			cri.andPhoneEqualTo(phone);
		}
		List<Owner> owners=ownerMapper.selectByExample(example);
		CommonResult result=new CommonResult(true);
		if(owners!=null&&owners.size()!=0)
		result.setData(owners.get(0));
		return result;
	}



	public CommonResult queryOwners(OwnerExample example) {
		List<Owner> owners=ownerMapper.selectByExample(example);
		CommonResult result=new CommonResult(true);
		result.setData(owners);
		return result;
	}

	  
	
	
}
